package cn.jy.generate.pojo;

import java.io.*;

/**
 * 每次通过自定义类加载器加载类时，都将从文件系统中读取类文件，而不会使用缓存的类文件。这能确保加载的是最新的类文件。
 */
public class CustomClassLoader extends ClassLoader {

    private String classPath;

    public CustomClassLoader(String classPath) {
        this.classPath = classPath;
    }

    @Override
    public Class<?> findClass(String name) throws ClassNotFoundException {
        // 生成类的路径（假设类文件是 ".class" 格式）
        String fileName = classPath + "/" + name.replace('.', '/') + ".class";
        File classFile = new File(fileName);

        if (!classFile.exists()) {
            throw new ClassNotFoundException("Class not found: " + fileName);
        }

        try {
            byte[] classData = loadClassData(classFile);
            return defineClass(name, classData, 0, classData.length);
        } catch (IOException e) {
            throw new ClassNotFoundException("Could not load class data", e);
        }
    }

    private byte[] loadClassData(File classFile) throws IOException {
        // 读取 .class 文件的字节内容
        try (FileInputStream fis = new FileInputStream(classFile);
             ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
            int data;
            while ((data = fis.read()) != -1) {
                baos.write(data);
            }
            return baos.toByteArray();
        }
    }
}

